from django.conf import settings
from django.utils import timezone
from django.db import transaction
from mysqldb.models import (
    AllinpayPlaceinterList,
    AllinpayPlaceinterLog,
    AllinpayPlacestaffList,
)
import hashlib


def hasHashCode(i, t):
    """计算hash值"""
    m = hashlib.md5()
    m.update(f"{t}{i}".encode("utf-8"))
    return m.hexdigest()


def addInter(bid, it, inter, rt, reqsn, status=0):
    """
    创建积分
    bid int 场所绑定员工ID
    it int 积分类型
    inter int 积分值
    rt str 事件类型
    reqsn int 事件单号(ID)
    status int 日志状态
    """

    try:
        bind = AllinpayPlacestaffList.objects.get(id=bid)
    except BaseException as err:
        return False

    with transaction.atomic():
        # django 事务
        t = timezone.now()
        try:
            l = AllinpayPlaceinterList.objects.get(
                pid=bind.pid, sid=bind.sid, intertype=it
            )
            f = l.intersum
            s = l.maxinter
            l.intersum = f + inter
            l.hash = hasHashCode(f + inter, settings.SECRET_KEY)
            if l.intersum > s:
                l.maxinter = l.intersum
                l.maxhash = hasHashCode(l.maxinter, settings.SECRET_KEY)
            l.currenttime = t
            l.save()
        except BaseException as err:
            f = 0
            AllinpayPlaceinterList(
                pid=bind.pid,
                sid=bind.sid,
                intertype=it,
                intersum=inter,
                hash=hasHashCode(inter, settings.SECRET_KEY),
                maxinter=inter,
                maxhash=hasHashCode(inter, settings.SECRET_KEY),
                currenttime=t,
            ).save()
        if not rt in ["积分兑换", "现金提现"]:
            # 创建日志
            AllinpayPlaceinterLog(
                pid=bind.pid,
                sid=bind.sid,
                intertype=it,
                inter=inter,
                intersum=f + inter,
                msgtype=rt,
                reqsn=reqsn,
                currenttime=t,
                status=status,
            ).save()
        return True
    return False
